//! @Author: DengLibin
//! @Date: Create in 2023-11-06 17:19:55
//! @Description: 路由

use axum::Router;
use axum::Extension;
use log::info;
use tower_http::services::ServeDir;

use std::sync::Arc;
use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, CorsLayer};

use crate::app::AppState;

use crate::sys::global::GlobalResult;

use super::{controller, midware};

/// @Author: DengLibin
/// @Date: Create in 2023-11-06 17:28:09
/// @Description: 创建路由
pub async fn new(app_state: AppState) -> GlobalResult<(Arc<AppState>, Router)> {
    let shared_state = Arc::new(app_state);

    let mut router = Router::new();

    //静态资源
    let serve_dir = ServeDir::new("static");
    router = router.nest_service("/static", serve_dir);
   
    //先注册接口
    router = controller::register_controller(router).await;
    info!("注册controller完成");

    //再注册中间件
    router = midware::register_middleware(router).await;
    info!("注册中间件完成");

    //再配置跨域
    let cors_layer = CorsLayer::new()
        .allow_origin(AllowOrigin::any())
        .allow_headers(AllowHeaders::any())
        .allow_methods(AllowMethods::any());

    router = router.layer(cors_layer);

    //共享状态
    router = router.layer(Extension(shared_state.clone()));

    Ok((shared_state, router))
}
